package com.mintyfresh.tns.server;

import java.net.*;
import java.io.*;
import java.util.*;
import com.mintyfresh.tns.util.*;

public class ServerListener extends Thread {

	private Socket socket = null;
	private ObjectOutputStream out = null;
	private ObjectInputStream in = null;
	private long session;
	private String client;

	public ServerListener(Socket socket, long session) {
		super("ServerListener");
		this.socket = socket;
		this.session = session;
	}

	public void run() {
		try {
			out = new ObjectOutputStream(socket.getOutputStream());
			in = new ObjectInputStream(socket.getInputStream());

			while (true) {
				Object o = in.readObject();
				if (!(o instanceof Message)) {
					System.err.println(
							"ERROR: OBJECT GIVEN TO SERVER LISTENER NOT VALID");
					break;
				}
				Message msg = (Message)o;
				if (msg.type().equals("newPlayer")) {
					Server.newPlayer(session, msg.getz("username"), out);}
				else if (msg.type().equals("shot")) {
					Server.receiveShot(
							session,
							msg.geti("power"),
							msg.geti("angle"));
				}
				else if (msg.type().equals("disconnect")) {
					Server.disconnect(session);}
			}
		} catch (Exception e) {
			if(e instanceof EOFException) {
				Server.disconnect(session);
			} else {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Kill command to stop the current thread
	 */
	public void kill() {
		try {
			System.out.println("calling stop");
			out.close();
			in.close();
			socket.close();
			Thread.currentThread().interrupt();
		} catch (Exception e) {
		}
	}
}
